package com.cmschina.mybatis;

import com.cmschina.custom.MapperContextHolder;
import com.cmschina.custom.MyCustomAnnotation;
import com.cmschina.custom.ThreadLocalHolder;
import com.cmschina.pojo.Event;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


@Component
@Intercepts({
        @Signature(
                type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class MybatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 获取执行方法的MappedStatement参数,不管是Executor的query方法还是update方法，第一个参数都是MappedStatement
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
//        String sqlId = mappedStatement.getId();
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();
//        long sqlStartTime = System.currentTimeMillis();
//        Object re = invocation.proceed();
//        long sqlEndTime = System.currentTimeMillis();
        // 打印mysql执行语句
        System.out.println(boundSql.getSql());

        // 获取Mapper接口方法
        Method method = MapperContextHolder.getCurrentMapperMethod(); // 假设ReflectUtil是一个自定义的工具类

        if (method != null && method.isAnnotationPresent(MyCustomAnnotation.class)) {
            MyCustomAnnotation trackedQuery = method.getAnnotation(MyCustomAnnotation.class);
            System.out.println("Method: " + method.getName() + ", Description: " + trackedQuery);
        }

        String database = ThreadLocalHolder.get();
        if (database != null) {
            switch (database) {
                case "mysql":
                    System.out.println("mysql 执行");
                    break;
                case "mysql1":
                    System.out.println("mysql1 执行");
                    break;
                default:
            }
        }


        List<Event> findAll = new ArrayList<>();
        Event event = new Event();
        event.setUser("12");
        findAll.add(event);
        // 继续执行原方法
        return findAll;
    }

    @Override
    public Object plugin(Object target) {
        System.out.println("Executing SQL: plugin");
        return Plugin.wrap(target, this);
    }
}